
import 'package:flutter/material.dart';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter_ahj_app/base/utils/oss/OSSUrlConsts.dart';
class NetOSSUtils {
  static BuildContext context = null;

  BaseOptions _options;
  Dio dio;

  // 工厂模式
  factory NetOSSUtils() => _getInstance();

  static NetOSSUtils get instance => _getInstance();
  static NetOSSUtils _instance;

  NetOSSUtils._internal() {
    //初始化
    dio = getDio();
  }

  static NetOSSUtils _getInstance() {
    if (_instance == null) {
      _instance = new NetOSSUtils._internal();
    }
    return _instance;
  }

  /**
   * 获取dio实例,不配置根url，完全使用传入的绝对路径url
   */
  Dio getDio({String url, BaseOptions options}) {
    if (options == null) {
      _options = new BaseOptions(
        baseUrl:OSSUrlConsts.URL_UPLOAD_IMAGE_OSS,
        connectTimeout: 15000,
        receiveTimeout: 15000,
        contentType: "application/x-www-form-urlencoded",
      );


      /*if (""==url ||
          (!url.startsWith("http://") && url.startsWith("https://"))) {

      } else {
        _options = new BaseOptions(
          connectTimeout: 15000,
          receiveTimeout: 15000,
          contentType: ContentType.parse("application/x-www-form-urlencoded"),
        );
      }*/
    } else {
      _options = options;
    }
    Dio _dio = new Dio(_options);
//    _dio.interceptors.add(new TokenInterceptor());//待完善
//    _dio.interceptors.add(new ErrorInterceptor(_dio));//待优化
//    _dio.interceptors.add(new HeaderInterceptor());
//    _dio.interceptors.add(new LogInterceptor());
//    setProxy(_dio);
    return _dio;
  }

  /**
   * 设置代理
   * */
  void setProxy(Dio dio) {
    //debug模式且为wifi网络时设置代理
   /* if (Config.debug) {
      //debug模式下设置代理
      (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
          (client) {
        //设置代理
        client.findProxy = (uri) {
          return "PROXY " + UrlConstant.PROXY_URI;
        };
      };
    }*/
  }

  post(BuildContext context, url, {data, BaseOptions options,cancelToken}) async {

    Response response;
    try {
      if (url != null &&
          (url.startsWith("http://") || url.startsWith("https://"))) {
        dio = getDio(url: url,options: options);
      }
      response = await dio.post(url, data: data, cancelToken: cancelToken);
    } on DioError catch (e) {
      if (CancelToken.isCancel(e)) {
      }
    }
    return response; //response.data.toString()这种方式不是标准json,不能使用
  }

  get(BuildContext context, url, {data,BaseOptions options,cancelToken}) async {
    Response response;
    try {
      if (url != null &&
          (url.startsWith("http://") || url.startsWith("https://"))) {
        dio = getDio(url: url,options: options);
      }
      response =
      await dio.get(url, queryParameters: data, cancelToken: cancelToken);
    } on DioError catch (e) {
      if (CancelToken.isCancel(e)) {
      }
    }
    return response;
  }
}